/**
 * @file: JacksonDemo.java
 *
 * @author: 蒋振
 *
 * @date: 2016年4月8日 上午11:37:18
 *
 * @copyright: 南京凯盛
 */
package cn.com.kisen.jiangz;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;


/**
 * 
 *
 * @author 蒋振
 * @version 1.0 Created on 2016年4月8日 上午11:37:18
 */
public class JacksonDemo {

    public void test() throws ParseException, IOException{

        User jackson = new User("jackson",8,new Date());
        User jacksonBro = new User("jackson jhon",7,new Date());
        System.out.println(jackson.toString());
        System.out.println(jacksonBro.toString());
        List<User> jacksons = new ArrayList<User>();
        jacksons.add(jackson);
        jacksons.add(jacksonBro);
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(jackson);
        System.out.println(json);
        String jsons = mapper.writeValueAsString(jacksons);
        System.out.println(jsons);
        
        User jacksonCopy = getUser(json);
        List<User> jacksonsCopy = getUsers(jsons);
        System.out.println(jacksonCopy.toString());
        for(User user : jacksonsCopy){
            System.out.println(user.toString());
        }
    }
    
    public User getUser(String userJSON){
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(userJSON, User.class);
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public List<User> getUsers(String usersJSON){
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(usersJSON, new TypeReference<List<User>>(){});
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
